package com.goodfox.web.generic.function.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.goodfox.web.generic.account.entity.Account;
import com.goodfox.web.generic.authority.entity.Resources;
import com.goodfox.web.generic.authority.service.PowerService;
import com.goodfox.web.generic.authority.service.ResourcesService;
import com.goodfox.web.generic.function.entity.Function;
import com.goodfox.web.generic.function.service.FunctionService;
import com.goodfox.web.generic.provide.exception.EntityValidateException;
import com.goodfox.web.generic.provide.service.EntityService;
import com.goodfox.web.generic.provide.util.AttributeUtil;
import com.goodfox.web.generic.provide.util.ParameterUtil;

@Controller
@RequestMapping("/function")
public class FunctionController {

	/** log4j日志器 */
	private Logger logger=Logger.getLogger(FunctionController.class);
	
	/** 权限Service */
	@Autowired
	private PowerService powerService;
	
	/** 系统功能Service */
	@Autowired
	private FunctionService functionService;
	
	/** 系统资源Service */
	@Autowired
	private ResourcesService resourcesService;
	
	/** 实体Service */
	@Autowired
	private EntityService entityService;

	/**
	 * 进入系统功能管理首页页面
	 * @return 目标页面
	 */
	@RequestMapping(value="goFunctionIndex.shtml")
	public String goFunctionIndex(HttpServletRequest request,ModelMap model){
		logger.info("进入系统功能管理首页");
		//判断是否有权限
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
	    	return "function/functionIndex";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 进入上级系统功能查找带回页面
	 * @return 目标页面
	 */
	@RequestMapping(value="goFunctionParentLookup.shtml")
	public String goFunctionParentLookup(HttpServletRequest request,ModelMap model){
		logger.info("进入上级系统功能查找带回页面");
		//判断是否有权限
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
	    	return "function/functionParentLookup";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	@RequestMapping(value="functionTreeQuery.shtml")
	@ResponseBody
	public Map functionTreeQuery(HttpServletRequest request){
		logger.info("执行系统功能查询");
		Map map=new HashMap();
	    Account loginAccount=(Account)request.getSession().getAttribute("loginAccount");
	    map.put("funList", functionService.queryFunctionListByScope(loginAccount.getRole().getRoleScope(),null));
		return map;
	}

	/**
	 * 进入系统功能查看页面
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="goFunctionDetail.shtml")
	public String goFunctionDetail(HttpServletRequest request,ModelMap model){
		logger.info("进入系统功能查看页面");
		model.put("fun",functionService.getFunction(ParameterUtil.getReqParaValue(request, "funId")));
		model.put("rseList",resourcesService.queryResourcesListByFunId(ParameterUtil.getReqParaValue(request, "funId")));
		return "function/functionDetail";
	}

	/**
	 * 进入系统资源查看页面
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="goResourcesDetail.shtml")
	public String goRresourcesDetail(HttpServletRequest request,ModelMap model){
		logger.info("进入系统资源查看页面");
		Resources rse=resourcesService.getResources(ParameterUtil.getReqParaValue(request, "rseId"));
		model.put("rse", rse);
		model.put("fun", functionService.getFunction(rse.getFunId()));
		return "resources/resourcesDetail";
	}
	
	/**
	 * 进入系统功能新增页面
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="goFunctionAdd.shtml")
	public String goFunctionAdd(HttpServletRequest request,ModelMap model){
		logger.info("进入系统功能新增页面");
	    Account loginAccount=powerService.havePower(request);
		if(loginAccount!=null){
			model.put("scopeList", AttributeUtil.queryAttrListByType("适用范围"));
			model.put("useList", AttributeUtil.queryAttrListByType("使用方式"));
			Function parentFun=functionService.getFunction(ParameterUtil.getReqParaValue(request, "funId"));
			model.put("parentFun", parentFun);
			return "function/functionAdd";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}

	/**
	 * 执行系统功能新增
	 * @param reqMap
	 * @return
	 */
	@RequestMapping(value="functionAdd.shtml")
	@ResponseBody
	public Map functionAdd(HttpServletRequest request){
		logger.info("执行系统功能新增");
		Map rspMap=new HashMap();
		rspMap.put("navTabId", "functionHome");
		rspMap.put("rel", "funShowPage");
		rspMap.put("callbackType", "");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				Function entity=(Function)entityService.fillEntity(request,Function.class);
				functionService.addFunction(entity,request.getSession().getAttribute("loginLogId").toString());
				statusCode="200";
				message="新增成功！";
			}catch(EntityValidateException evex){
				message="新增失败:"+evex.getMessage()+"！";
			}catch(Exception ex){
				logger.error("functionAdd异常：",ex);
				message="新增失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("functionAdd rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 进入系统资源新增页面
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="goResourcesAdd.shtml")
	public String goResourcesAdd(HttpServletRequest request,ModelMap model){
		logger.info("进入系统资源新增页面");
	    Account loginAccount=powerService.havePower(request);
		if(loginAccount!=null){
			model.put("typeList", AttributeUtil.queryAttrListByType("资源类型"));
			Function fun=functionService.getFunction(ParameterUtil.getReqParaValue(request, "funId"));
			model.put("fun", fun);
			return "resources/resourcesAdd";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}

	/**
	 * 执行系统资源新增
	 * @param reqMap
	 * @return
	 */
	@RequestMapping(value="resourcesAdd.shtml")
	@ResponseBody
	public Map resourcesAdd(HttpServletRequest request){
		logger.info("执行系统资源新增");
		Map rspMap=new HashMap();
		rspMap.put("navTabId", "functionHome");
		rspMap.put("rel", "rseShowPage");
		rspMap.put("callbackType", "");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				Resources entity=(Resources)entityService.fillEntity(request,Resources.class);
				resourcesService.addResources(entity,request.getSession().getAttribute("loginLogId").toString());
				statusCode="200";
				message="新增成功！";
			}catch(EntityValidateException evex){
				message="新增失败:"+evex.getMessage()+"！";
			}catch(Exception ex){
				logger.error("resourcesAdd异常：",ex);
				message="新增失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("resourcesAdd rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 进入系统功能修改页面
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="goFunctionModify.shtml")
	public String goFunctionModify(HttpServletRequest request,ModelMap model){
		logger.info("进入系统功能修改页面");
	    Account loginAccount=powerService.havePower(request);
		if(loginAccount!=null){
			model.put("scopeList", AttributeUtil.queryAttrListByType("适用范围"));
			model.put("useList", AttributeUtil.queryAttrListByType("使用方式"));
			model.put("stateList", AttributeUtil.queryAttrListByType("状态"));
			Function fun=functionService.getFunction(ParameterUtil.getReqParaValue(request, "funId"));
			model.put("fun", fun);
			model.put("parentFun", functionService.getFunction(fun.getFunIdParent()));
			return "function/functionModify";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}

	/**
	 * 执行系统功能更新
	 * @param reqMap
	 * @return
	 */
	@RequestMapping(value="functionModify.shtml")
	@ResponseBody
	public Map functionModify(HttpServletRequest request){
		logger.info("执行系统功能更新");
		Map rspMap=new HashMap();
		rspMap.put("navTabId", "functionHome");
		rspMap.put("rel", "funShowPage");
		rspMap.put("callbackType", "");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				Function newEny=(Function)entityService.fillEntity(request,Function.class);
				Function oldEny=functionService.getFunction(newEny.getFunId());
				functionService.modifyFunction(oldEny,newEny,request.getSession().getAttribute("loginLogId").toString());
				statusCode="200";
				message="更新成功！";
			}catch(EntityValidateException evex){
				message="更新失败:"+evex.getMessage()+"！";
			}catch(Exception ex){
				logger.error("functionModify异常：",ex);
				message="更新失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("functionModify rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 进入系统资源修改页面
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="goResourcesModify.shtml")
	public String goResourcesModify(HttpServletRequest request,ModelMap model){
		logger.info("进入系统资源修改页面");
	    Account loginAccount=powerService.havePower(request);
		if(loginAccount!=null){
			model.put("typeList", AttributeUtil.queryAttrListByType("资源类型"));
			model.put("stateList", AttributeUtil.queryAttrListByType("状态"));
			Resources rse=resourcesService.getResources(ParameterUtil.getReqParaValue(request, "rseId"));
			model.put("rse", rse);
			Function fun=functionService.getFunction(rse.getFunId());
			model.put("fun", fun);
			return "resources/resourcesModify";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}

	/**
	 * 执行系统资源更新
	 * @param reqMap
	 * @return
	 */
	@RequestMapping(value="resourcesModify.shtml")
	@ResponseBody
	public Map resourcesModify(HttpServletRequest request){
		logger.info("执行系统资源更新");
		Map rspMap=new HashMap();
		rspMap.put("navTabId", "functionHome");
		rspMap.put("rel", "rseShowPage");
		rspMap.put("callbackType", "");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				Resources newEny=(Resources)entityService.fillEntity(request,Resources.class);
				Resources oldEny=resourcesService.getResources(newEny.getRseId());
				resourcesService.modifyResources(oldEny,newEny,request.getSession().getAttribute("loginLogId").toString());
				statusCode="200";
				message="更新成功！";
			}catch(EntityValidateException evex){
				message="更新失败:"+evex.getMessage()+"！";
			}catch(Exception ex){
				logger.error("resourcesModify异常：",ex);
				message="更新失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("resourcesModify rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 执行系统功能删除操作，数据物理删除
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="functionRemove.shtml")
	@ResponseBody
	public Map functionRemove(HttpServletRequest request){
		logger.info("执行系统功能移除");
		Map rspMap=new HashMap();
		rspMap.put("navTabId", "functionHome");
		rspMap.put("rel", "funShowPage");
		rspMap.put("callbackType", "");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				Function entity=functionService.getFunction(ParameterUtil.getReqParaValue(request, "funId"));
				boolean isExec=true;
				if(isExec){
					if(entity.getSubCount()>0){
						isExec=false;
						message="该功能中有下级功能，不能移除！";
					}
				}
				if(isExec){
					if(entity.getRseCount()>0){
						isExec=false;
						message="该功能中有资源信息，不能移除！";
					}
				}
				if(isExec){
					if(entity.getRoleCount()>0){
						isExec=false;
						message="该功能中已绑定角色，不能移除！";
					}
				}
				if(isExec){
					functionService.removeFunction(entity,request.getSession().getAttribute("loginLogId").toString());
					statusCode="200";
					message="移除成功！";
				}
			}catch(Exception ex){
				logger.error("functionRemove异常：",ex);
				message="移除失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("functionRemove rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 执行系统资源删除操作，数据物理删除
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="resourcesRemove.shtml")
	@ResponseBody
	public Map resourcesRemove(HttpServletRequest request){
		logger.info("执行系统功能移除");
		Map rspMap=new HashMap();
		rspMap.put("navTabId", "functionHome");
		rspMap.put("rel", "rseShowPage");
		rspMap.put("callbackType", "");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				Resources entity=resourcesService.getResources(ParameterUtil.getReqParaValue(request, "rseId"));
				resourcesService.removeResources(entity,request.getSession().getAttribute("loginLogId").toString());
				statusCode="200";
				message="移除成功！";
			}catch(Exception ex){
				logger.error("functionRemove异常：",ex);
				message="移除失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("resourcesRemove rspMap:"+rspMap);
		return rspMap;
	}
}
